import store from '@/store';
import { getToken, removeToken, setToken } from '@/utils/auth.ts';
import { getInfo, login, logout } from '@/api/system/login.ts';
import { MessagePlugin } from 'tdesign-vue-next';

export const useUserStore = defineStore('user', () => {
  // state
  const state = reactive<{
    token: string | null;
    id: string;
    name: string;
    avatar: any;
    roles: any[];
    permissions: any[];
    operateId: string;
    userinfo: any;
  }>({
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    operateId: '',
    userinfo:
      (localStorage.getItem('USER_USERINFO') &&
        JSON.parse(localStorage.getItem('USER_USERINFO') || '{}')) ||
      {},
  });

  // mutations
  const SET_TOKEN = (token: string) => {
    state.token = token;
  };
  const SET_ID = (id: string) => {
    state.id = id;
  };
  const SET_NAME = (name: string) => {
    state.name = name;
  };
  const SET_AVATAR = (avatar: string) => {
    state.avatar = avatar;
  };
  const SET_ROLES = (roles: any[]) => {
    state.roles = roles;
  };
  const SET_PERMISSIONS = (permissions: any[]) => {
    state.permissions = permissions;
  };
  const SET_OPERATEID = (operateId: string) => {
    state.operateId = operateId;
  };
  const SET_USERINFO = (userinfo: any) => {
    state.userinfo = userinfo;
    localStorage.setItem('USER_USERINFO', JSON.stringify(userinfo));
  };

  // actions
  const Login = (userInfo: object) => {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then((res) => {
          if (res.data.code === 200) {
            setToken(res.data.token);
            SET_TOKEN(res.data.token);
            resolve(null);
          } else {
            void MessagePlugin.error(res.data.msg);
            reject(res.data);
          }
        })
        .catch((err) => {
          void MessagePlugin.error(err);
          reject(err);
        });
    });
  };
  const GetInfo = () => {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((_res) => {
          if (_res.data.code === 200) {
            const res = _res.data;
            const user = res.user;
            const avatar: any =
              user.avatar == '' || user.avatar == null
                ? import.meta.glob('@/asstes/images/profile.jpg')
                : __APP_ENV__.VITE_APP_API + user.avatar;
            const operateId = res.operateId;
            if (res.roles && res.roles.length > 0) {
              SET_ROLES(res.roles);
              SET_PERMISSIONS(res.permissions);
            } else {
              SET_ROLES(['ROLE_DEFAULT']);
            }
            SET_ID(user.userId);
            SET_NAME(user.userName);
            SET_AVATAR(avatar);
            SET_OPERATEID(operateId);
            SET_USERINFO(res);
            resolve(res);
          } else {
            void MessagePlugin.error(_res.data.msg);
            reject(_res.data);
          }
        })
        .catch((err) => {
          void MessagePlugin.error(err);
          reject(err);
        });
    });
  };
  const LogOut = () => {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          SET_ID('');
          SET_NAME('');
          SET_AVATAR('');
          SET_OPERATEID('');
          SET_TOKEN('');
          SET_ROLES([]);
          SET_PERMISSIONS([]);
          SET_USERINFO({});
          localStorage.clear();
          removeToken();
        })
        .finally(() => {
          resolve(null);
        });
    });
  };
  // getters
  const userinfo_getter = computed(() => state.userinfo);

  return {
    ...toRefs(state),
    userinfo_getter,
    Login,
    GetInfo,
    LogOut,
  };
});

// 在组件外部用pinia就调用这个方法
export function useUserStoreWithOut() {
  return useUserStore(store);
}
